<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :page.sync="page"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
          <template slot-scope="scope" slot="menu">
            <el-button type="text" icon="el-icon-refresh" size="small" @click.stop="handlerPassword(scope.row.id)">密码重置</el-button>
          </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  getUser,
  getList,
  remove,
  update,
  grant,
  resetPassword,
  getDeptTree,
  getRoleTree,
} from "@/api/user";
import { addUser } from "@/api/system";

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      selectionList: [],
      roleIddicData: [],
      deptIddicData: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      data: [],
    };
  },
  watch: {},
  computed: {
    addBtnShow() {
      return true;
    },
    option() {
      return {
        addBtn: this.addBtnShow,
        editBtn: this.addBtnShow,
        delBtn: false,
        refreshBtn: false,
        columnBtn: false,
        // height: "auto",
        // calcHeight: 80,
        // searchShow: true,
        searchMenuSpan: 6,
        // border: true,
        // index: true,
        // selection: true,
        column: [
          {
            label: "登录账号",
            prop: "account",
            search: true,
            rules: [
              { required: true, message: "请输入登录账号", trigger: "blur" },
            ],
          },
          {
            label: "用户姓名",
            prop: "name",
            search: true,
            rules: [
              { required: true, message: "请输入用户姓名", trigger: "blur" },
            ],
          },
          {
            label: "密码",
            prop: "password",
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            // rules: [{required: true, validator: validatePass, trigger: 'blur'}]
          },
          {
            label: "确认密码",
            prop: "password2",
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            // rules: [{required: true, validator: validatePass2, trigger: 'blur'}]
          },
          {
            label: "手机号码",
            prop: "phone",
          },
          {
            label: "邮箱",
            prop: "email",
          },

          {
            label: "所属角色",
            // hide: true,
            prop: "roleId",
            type: "select",
            multiple: true,
            dicData: this.roleIddicData,
            props: {
              value: "key",
              label: "title",
            },
            rules: [
              {
                required: true,
                message: "请选择所属角色",
                trigger: "click",
              },
            ],
          },
          {
            label: "所属部门",
            // hide: true,
            prop: "deptId",
            type: "tree",
            multiple: true,
            // multiple: true,
            dicData: this.deptIddicData,
            props: {
              value: "key",
              label: "title",
            },
            rules: [
              {
                required: true,
                message: "请选择所属部门",
                trigger: "click",
              },
            ],
          },
        ],
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted() {
    // 非租户模式默认加载管理组数据
    this.initData();
  },
  methods: {
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getUser(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },

    initData() {
      getRoleTree().then((res) => {
        this.roleIddicData = res.data.data;
      });
      getDeptTree().then((res) => {
        this.deptIddicData = res.data.data;
      });
    },
    submitRole() {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
      grant(this.ids, roleList).then(() => {
        this.roleBox = false;
        this.$message({
          type: "success",
          message: "操作成功!",
        });
        this.onLoad(this.page);
      });
    },
    rowSave(row, done, loading) {
      row.deptId = row.deptId.join(",");
      row.roleId = row.roleId.join(",");
      addUser(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        }, () => {
          loading();
        });
    },
    rowUpdate(row, index, done, loading) {
      row.deptId = row.deptId.join(",");
      row.roleId = row.roleId.join(",");
      update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        }, () => {
          loading();
        });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handlerPassword(id) {
      this.$confirm("确定将账号重置密码?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return resetPassword(id);
        })
        .then((res) => {
          if (res.data.success) {
            this.$alert(res.data.data, "重置密码成功");
          } else {
            this.$message({ type: "warning", message: res.data.msg });
          }
        });
    },

    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage,page.pageSize,Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        let records = data.records;
        let dataList = [];
        for (let i = 0; i < records.length; i++) {
          let dataItem = records[i];
          if (dataItem.hasOwnProperty("deptId")) {
            dataItem.deptId = dataItem.deptId.split(",");
          }
          if (dataItem.hasOwnProperty("roleId")) {
            dataItem.roleId = dataItem.roleId.split(",");
          }
          dataList.push(dataItem);
        }
        this.data = dataList;
        this.page.total = data.total;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>
